package com.nopay.dxdwphone.ui.ativity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseActivity;
import com.nopay.dxdwphone.bean.request.SaveCallDataRequest;
import com.nopay.dxdwphone.bean.response.SaveCallDataResponse;
import com.nopay.dxdwphone.contact.a_z.BeanPhoneDto;
import com.nopay.dxdwphone.contact.a_z.PinyinPhone;
import com.nopay.dxdwphone.contact.a_z.PinyinUtils;
import com.nopay.dxdwphone.contact.a_z.SideBar;
import com.nopay.dxdwphone.dialog.DialogLoading;
import com.nopay.dxdwphone.dialog.DialogPleaseOpenCallSetting;
import com.nopay.dxdwphone.dialog.DialogWaitCallTransferSetting;
import com.nopay.dxdwphone.receiver.PhoneBroadcastReceiver;
import com.nopay.dxdwphone.utils.CallLogHelper;
import com.nopay.dxdwphone.utils.CallTransferUtil;
import com.nopay.dxdwphone.utils.MemberManager;
import com.nopay.dxdwphone.utils.PhoneUtil;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.nopay.dxdwphone.CallGroupEnum;
import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.ActivityPhoneBookBinding;

import com.nopay.dxdwphone.ui.adapter.PhoneNameAdapter;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 创 建 人 PeaceJay
 * 创建时间 2019/4/10
 * 类 描 述：通讯录
 */
public class PhoneBookActivity extends BaseActivity<ActivityPhoneBookBinding> {

    private List<BeanPhoneDto> phoneDtos;
    private PhoneNameAdapter adapter;
    private String[] stringId, stringName;
    private JSONArray jsonArray;
    private String telPhone;

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(PhoneBookActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(v -> mSwipeBackHelper.backward());

        requestPermission();
        binding.refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestPermission();
                binding.tvQhLogin.setText("");
                refreshLayout.finishRefresh(500);
                refreshLayout.resetNoMoreData();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {

            }
        });


        //根据输入框输入值的改变来过滤搜索
        binding.tvQhLogin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        getCallLog(0);
    }


    private void setAdapter() {
        Collections.sort(phoneDtos, new PinyinPhone());
        adapter = new PhoneNameAdapter(this, phoneDtos);
        binding.lvContact.setAdapter(adapter);
        //listview点击
        binding.lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(!MemberManager.hasMemberPermission()) {
                    if(!MemberManager.hasFreeTimes()) {
                        ToastUtils.showShort("今日免费次数已用完");

//                        new DialogPleaseOpenMember(PhoneBookActivity.this).setOnOpenMemberConfirmListener(() -> {
//                            mSwipeBackHelper.forward(RechargeActivity.class);
//                        }).show();
                        return;
                    }
                }

                if(!SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false)) {
                    new DialogPleaseOpenCallSetting(PhoneBookActivity.this).setOnOpenCallSettingConfirmListener(() -> {
                        // TODO 开启防封设置
                        mSwipeBackHelper.forward(CallSettingActivity.class);
                    }).show();
                    return;
                }

                MemberManager.addUseTimes();

                BeanPhoneDto item = (BeanPhoneDto) adapter.getItem(position);
                telPhone = item.getTelPhone();

                if(CallTransferUtil.open(PhoneBookActivity.this, telPhone)) {
                    if(SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                        initDianXinCallFinishListener(telPhone);
                    } else {
                        initCallFinishListener(telPhone);
                        new DialogWaitCallTransferSetting(PhoneBookActivity.this)
                                .setOnWaitFinishListener(() -> CallTransferUtil.call(PhoneBookActivity.this, ""))
                                .show(SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TIME_OUT, Constants.CALL_TRANSFER_DEFAULT_TIME_OUT));
                    }
                } else {
                    initCallFinishListener(telPhone);
                    CallTransferUtil.call(PhoneBookActivity.this, telPhone);
                }
            }
        });

        //设置右侧触摸监听
        binding.sidrbar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    binding.lvContact.setSelection(position);
                    //中间显示提示
                    binding.sidrbar.setTextView(binding.dialog);
                }
            }
        });
    }


    /**
     * Request permissions.
     */
    private void requestPermission() {
        requetPermission(2);
    }


    private List<BeanPhoneDto> filledData(String[] stringId, String[] stringName) {
        List<BeanPhoneDto> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();
        for (int i = 0; i < stringId.length; i++) {
            BeanPhoneDto sortModel = new BeanPhoneDto();
            sortModel.setTelPhone(stringId[i]);
            sortModel.setName(stringName[i]);
            String pinyin = PinyinUtils.getPingYin(stringName[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            }
            mSortList.add(sortModel);
        }
        Collections.sort(indexString);
        binding.sidrbar.setIndexText(indexString);
        return mSortList;
    }


    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<BeanPhoneDto> mSortList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            mSortList = phoneDtos;
        } else {
            mSortList.clear();
            for (BeanPhoneDto sortModel : phoneDtos) {
                String name = sortModel.getName();
                if (name.toUpperCase().indexOf(filterStr.toUpperCase()) != -1
                        || PinyinUtils.getPingYin(name).toUpperCase().startsWith(filterStr.toUpperCase())) {
                    mSortList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(mSortList, new PinyinPhone());
        adapter.updateListView(mSortList);
    }

    private void requetPermission(int request) {
        if (request == 1){
            if (ContextCompat.checkSelfPermission(PhoneBookActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(PhoneBookActivity.this, new String[]{Manifest.permission.CALL_PHONE}, request);
            }else{
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telPhone));
                startActivity(intent);
            }
        }
       if (request == 2){
           if (ContextCompat.checkSelfPermission(PhoneBookActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
               ActivityCompat.requestPermissions(PhoneBookActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, request);
           }else{
               //授权成功
               //成功
               PhoneUtil phoneUtil = new PhoneUtil(PhoneBookActivity.this);
               phoneDtos = phoneUtil.getPhone();
               jsonArray = new JSONArray();
               /*虚拟数据*/
               ArrayList<String> qyidArrayList = new ArrayList<String>();
               ArrayList<String> stringArrayList = new ArrayList<String>();

               for (int j = 0; j < phoneDtos.size(); j++) {
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("name", phoneDtos.get(j).getName());
                   jsonObject.put("phone", phoneDtos.get(j).getTelPhone());
                   jsonArray.add(jsonObject);

                   String str = phoneDtos.get(j).getName();
                   if (!str.equals("")) {
                       str = str.substring(0, 1);
                       if (PhoneUtil.isChinese(str)) {
                           stringArrayList.add(phoneDtos.get(j).getName());
                       } else {
                           stringArrayList.add("Z(" + phoneDtos.get(j).getName() + ")");
                       }
                       qyidArrayList.add(phoneDtos.get(j).getTelPhone());
                   }

               }
               stringId = qyidArrayList.toArray(new String[qyidArrayList.size()]);
               stringName = stringArrayList.toArray(new String[stringArrayList.size()]);
//                        Logger.e("1111111", "onCLick: "+ jsonArray.toString());
               phoneDtos = filledData(stringId, stringName);
               //更新界面
               setAdapter();
           }
       }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {//选择了“始终允许”
                    ToastUtils.showShort("" + "权限" + permissions[i] + "申请成功");
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telPhone));
                    startActivity(intent);
                } else {
                    ToastUtils.showShort("请给用户授权");
                }
            }
        }

        if (requestCode == 2) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {//选择了“始终允许”
                    ToastUtils.showShort("" + "权限" + permissions[i] + "申请成功");
                    //授权成功
                    //成功
                    PhoneUtil phoneUtil = new PhoneUtil(PhoneBookActivity.this);
                    phoneDtos = phoneUtil.getPhone();
                    jsonArray = new JSONArray();
                    /*虚拟数据*/
                    ArrayList<String> qyidArrayList = new ArrayList<String>();
                    ArrayList<String> stringArrayList = new ArrayList<String>();

                    for (int j = 0; j < phoneDtos.size(); j++) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("name", phoneDtos.get(j).getName());
                        jsonObject.put("phone", phoneDtos.get(j).getTelPhone());
                        jsonArray.add(jsonObject);

                        String str = phoneDtos.get(j).getName();
                        if (!str.equals("")) {
                            str = str.substring(0, 1);
                            if (PhoneUtil.isChinese(str)) {
                                stringArrayList.add(phoneDtos.get(j).getName());
                            } else {
                                stringArrayList.add("Z(" + phoneDtos.get(j).getName() + ")");
                            }
                            qyidArrayList.add(phoneDtos.get(j).getTelPhone());
                        }

                    }
                    stringId = qyidArrayList.toArray(new String[qyidArrayList.size()]);
                    stringName = stringArrayList.toArray(new String[stringArrayList.size()]);
//                        Logger.e("1111111", "onCLick: "+ jsonArray.toString());
                    phoneDtos = filledData(stringId, stringName);
                    //更新界面
                    setAdapter();
                } else {
                    ToastUtils.showShort("请给用户授权");
                }
            }
        }
    }

    public void initDianXinCallFinishListener(String phoneNumber) {
        PhoneBroadcastReceiver.setOnCallFinishListener((status, callLogItem) -> {
            if(status == 1) {
                new Handler().postDelayed(() -> {
                    initCallFinishListener(phoneNumber);
                    CallTransferUtil.call(PhoneBookActivity.this, "");
                }, 100);
            }
        });
    }

    public void initCallFinishListener(String phoneNumber) {
        PhoneBroadcastReceiver.setOnCallFinishListener((status, callLogItem) -> {
            if(status == 0) {
                if(!isFinishing()) {
                    if(mLoading == null) mLoading = new DialogLoading(PhoneBookActivity.this);
                    mLoading.show("正在保存通话记录...");
                }
            }

            if(status == 1) {
                if(callLogItem != null) {
                    // 保存通话记录
                    saveCallData(phoneNumber, callLogItem.getDate(), callLogItem.getDuration(), 0);
                } else {
                    // 保存通话记录
                    @SuppressLint("SimpleDateFormat") String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    saveCallData(phoneNumber, dateStr, 0, 0);
                }

                if(!SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                    boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
                    if(isOpen && !isFinishing()) CallTransferUtil.close(PhoneBookActivity.this);
                }
            }

//            if(mLoading == null) mLoading = new DialogLoading(PhoneBookActivity.this);
//            mLoading.show("正在保存通话记录...");
//
//            new Thread(() -> {
//                CallLogHelper.CallLogItem callLogItem = getCallLog(5);
//                if(callLogItem != null) {
//                    // 保存通话记录
//                    saveCallData(phoneNumber, callLogItem.getDate(), callLogItem.getDuration(), 0);
//                } else {
//                    @SuppressLint("SimpleDateFormat") String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//                    saveCallData(phoneNumber, dateStr, 0, 0);
//                }
//
//                boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
//                if(isOpen) CallTransferUtil.close(PhoneBookActivity.this);
//            }).start();
        });
    }

    private CallLogHelper.CallLogItem getCallLog(int times) {
        CallLogHelper.CallLogItem callLogItem = CallLogHelper.fetchNewCallLog(PhoneBookActivity.this);
        if(callLogItem == null) {
            if(times > 0) {
                times--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCallLog(times);
            }
        }
        return callLogItem;
    }

    private DialogLoading mLoading;

    public void saveCallData(String phoneNumber, String dateStr, int duration, int saveTimes) {
        SaveCallDataRequest bean = new SaveCallDataRequest();
        bean.setCallDate(dateStr);
        bean.setCalledNumber(phoneNumber);
//                    String callingNumber = CallTransferUtil.getPhoneNumberBySubId(PhoneBookActivity.this, subId);
        String callingNumber = CallTransferUtil.getPhoneNumberByCallSetting();
        bean.setCallingNumber("".equals(callingNumber) ? "未知" : callingNumber);
        bean.setCompany("");
        bean.setDuration(duration);
        bean.setName("");
        bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
        bean.setStatus(duration > 0 ? 1 : 2);
        bean.setTaskId(CallGroupEnum.IMPORT_MANUAL.getGroupId());

        RequestBody body = getRequestBody(bean);
        api.doSaveCallData(body).enqueue(new Callback<SaveCallDataResponse>() {
            @Override
            public void onResponse(Call<SaveCallDataResponse> call, Response<SaveCallDataResponse> response) {
                if(mLoading != null) {
                    mLoading.dismiss();
                    mLoading = null;
                }

                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        ToastUtils.showShort("通话记录已保存");
                        return;
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
                if(saveTimes < 3) new Handler().postDelayed(() -> saveCallData(phoneNumber, dateStr, duration, saveTimes + 1), 3000);
            }

            @Override
            public void onFailure(Call<SaveCallDataResponse> call, Throwable t) {
                if(mLoading != null) {
                    mLoading.dismiss();
                    mLoading = null;
                }

                ToastUtils.showShort(getResources().getString(R.string.call_api_error));
                if(saveTimes < 3) new Handler().postDelayed(() -> saveCallData(phoneNumber, dateStr, duration, saveTimes + 1), 3000);
            }
        });
    }
}